import { AnyAction } from "redux";
import * as types from "../action-types"
import LoginTypes from "../../typings/login-types"

export interface ProfileState {
    name: string;
    loginState:LoginTypes,
    user:any,
    error:string | null,
}

let initialState: ProfileState = {
    name: "profile",
    loginState:LoginTypes.UN_VALIDATE,
    user: null,
    error: null
};

function reducer (state: ProfileState = initialState, action: AnyAction) {
    switch (action.type) {
        case types.VALIDATE:
          if (action.payload.success) {
            return {
              ...state,
              loginState: LoginTypes.LOGINED,
              user: action.payload.user,
              error: null, 
            };
          } else {
            return {
              ...state,
              loginState: LoginTypes.UNLOGIN,
              user: null,
              error:  action.payload.message
            };
          }
          case types.LOGOUT:
            return {
              ...state,
              loginState: LoginTypes.UN_VALIDATE,
              user: null,
              error: null,
            }
        case types.CHANGE_AVATAR:
          return {
            ...state,
            user:{
              ...state.user,
              avatar:action.payload
            }
          }    
        default:
          return state;
        }
};
export default reducer;
